﻿using UnityEngine;
using System;

namespace SangsTools
{
    public class SingletonScriptable<T> : ScriptableObject where T : SingletonScriptable<T>
    {
        private static T instance;
        public static T Ins
        {
            get
            {
                if (instance == null)
                {
                    PathAttribute path = GetPathAttribute();
                    if (path != null)
                    {
                        instance = Resources.Load<T>(path.Path);
                        if (instance == null)
                        {
                            throw new Exception($"路径错误 没找到 {typeof(T) } path={ path.Path}");
                        }
                        else
                        {
                            instance.OnFirstLoad();
                        }
                    }
                }
                return instance;
            }
        }

        protected virtual void OnFirstLoad() { }

        private static PathAttribute GetPathAttribute()
        {
            Type type = typeof(T);
            object[] attributes = type.GetCustomAttributes(typeof(PathAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0] as PathAttribute;
            }
            else
            {
                throw new Exception($"{type} 必须要有Path属性");
            }
        }
    }
}
